import 'dart:async';

import 'package:dmz/base/pageWidget/base_stateful_widget.dart';
import 'package:dmz/base/widget/defult_widget.dart';
import 'package:dmz/business/home/controller/add_moto_controller.dart';
import 'package:dmz/business/login/widgets/login_widgets.dart';
import 'package:dmz/string_res/str_res_keys.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class ScanResultWidget extends StatefulWidget {
  final int type;
  const ScanResultWidget({super.key, required this.type});

  @override
  State<ScanResultWidget> createState() => _ScanResultWidgetState();
}

class _ScanResultWidgetState extends State<ScanResultWidget> {
  @override
  Widget build(BuildContext context) {
    return getMainWidget();
  }

  Widget getMainWidget() {
    switch (widget.type) {
      case 0:
        return ontOpenBlueWidget();
      case 1:
        return scanResultWidget();
      case 2:
        return contentSuccess();
      case 3:
        return noScanDevice();
      default:
        return ontOpenBlueWidget();
    }
  }

  ///扫描设备列表
  Widget scanResultWidget() {
    return GetBuilder<AddBikeController>(
        id: 'scanResult',
        builder: (controlle) {
          return controlle.contentFinished
              ? ScanResulOthertWidget.contentSuccessChild(controlle.timerNum)
              : Container(
                  decoration: BoxDecoration(
                    color: const Color(0xFF434650),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(60.sp),
                      topRight: Radius.circular(60.sp),
                    ),
                  ),
                  child: Column(mainAxisSize: MainAxisSize.min, children: [
                    Row(children: [
                      DefaultText('设备列表'.tr, 40.sp, textColor: Colors.white)
                          .marginOnly(left: 32.sp),
                      const Expanded(child: SizedBox()),
                      Image.asset('assets/images/home/main/close_icon.png',
                              width: 36.sp, height: 36.sp)
                          .marginOnly(right: 36.sp)
                    ])
                        .marginOnly(top: 60.sp, bottom: 60.sp)
                        .addGestureDetector(() => Get.back()),
                    Container(
                        constraints: BoxConstraints(maxHeight: 1000.sp),
                        child: ListView.builder(
                            shrinkWrap: true,
                            itemCount: controlle.listData.length,
                            itemBuilder: (context, index) {
                              return scanResultItem(
                                  controlle.listData[index],
                                  () => controlle.checkBluetooth(
                                      controlle.listData[index]));
                            }).marginOnly(bottom: 106.sp))
                  ]));
        });
  }

  Widget scanResultItem(ScanResult data, Function() click) {
    return Column(children: [
      Container(
          height: 192.sp,
          child: Row(children: [
            SizedBox(width: 32.sp),
            Image.asset('assets/images/home/scan/V50.png',
                width: 112.sp, height: 112.sp),
            SizedBox(width: 32.sp),
            DefaultText(data.device.advName, 48.sp,
                textColor: Colors.white, fontWeight: FontWeight.w600),
            const Expanded(child: SizedBox()),
            LoginWidgets.loginOtherBtn(context, click,
                width: 204.sp, hight: 76.sp, title: '立即配对'.tr, textSize: 28.sp),
          ])).marginOnly(right: 32.sp),
      Container(
          margin: EdgeInsets.only(left: 32.sp, right: 32.sp),
          height: 2.sp,
          color: const Color(0xFFD8D8D8)),
    ]).marginOnly(right: 32.sp);
  }

  ///扫描提示
  Widget ontOpenBlueWidget() {
    return Container(
        alignment: Alignment.center,
        height: 928.sp,
        decoration: BoxDecoration(
          color: const Color(0xFF434650),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(60.sp),
            topRight: Radius.circular(60.sp),
          ),
        ),
        child: Column(children: [
          Row(children: [
            const Expanded(child: SizedBox()),
            Image.asset('assets/images/home/main/close_icon.png',
                    width: 36.sp, height: 36.sp)
                .marginOnly(right: 36.sp)
          ])
              .marginOnly(top: 60.sp, bottom: 60.sp)
              .addGestureDetector(() => Get.back()),
          Container(
              margin: EdgeInsets.only(left: 32.sp, right: 32.sp),
              height: 2.sp,
              color: const Color(0xFFD8D8D8)),
          Image.asset('assets/images/home/main/blue_image.png',
                  width: 400.sp, height: 334.sp)
              .marginOnly(top: 84.sp),
          DefaultText('当前为蓝牙未打开'.tr, 40.sp, textColor: Colors.white)
        ]));
  }

  ///扫描提示
  Widget noScanDevice() {
    return Container(
        alignment: Alignment.center,
        height: 928.sp,
        decoration: BoxDecoration(
          color: const Color(0xFF434650),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(60.sp),
            topRight: Radius.circular(60.sp),
          ),
        ),
        child: Column(children: [
          Row(children: [
            const Expanded(child: SizedBox()),
            Image.asset('assets/images/home/main/close_icon.png',
                    width: 36.sp, height: 36.sp)
                .marginOnly(right: 36.sp)
          ])
              .marginOnly(top: 60.sp, bottom: 60.sp)
              .addGestureDetector(() => Get.back()),
          Container(
              margin: EdgeInsets.only(left: 32.sp, right: 32.sp),
              height: 2.sp,
              color: const Color(0xFFD8D8D8)),
          Image.asset('assets/images/home/main/blue_image.png',
                  width: 400.sp, height: 334.sp)
              .marginOnly(top: 84.sp),
          DefaultText('未发现设备'.tr, 40.sp,
              textColor: Colors.white, fontWeight: FontWeight.w700),
          DefaultText(
                  '1、未发现想要的设备，可尝试重新扫描 \n2、检查当前环境信号强度，并尝试靠近蓝牙设备 \n3、检查当前手机定位权限是否打开'
                      .tr,
                  32.sp,
                  textColor: Colors.white,
                  fontWeight: FontWeight.w700)
              .marginOnly(top: 30.sp)
        ]));
  }

  ///链接完成
  Widget contentSuccess() {
    return GetBuilder<AddBikeController>(
        id: 'scanResult',
        builder: (controlle) {
          return ScanResulOthertWidget.contentSuccessChild(controlle.timerNum);
        });
  }
}

class ScanResulOthertWidget {
  static Widget contentSuccessChild(timerNum) {
    return Container(
        alignment: Alignment.center,
        height: 928.sp,
        decoration: BoxDecoration(
          color: const Color(0xFF434650),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(60.sp),
            topRight: Radius.circular(60.sp),
          ),
        ),
        child: Column(children: [
          Row(children: [
            const Expanded(child: SizedBox()),
            Image.asset('assets/images/home/main/close_icon.png',
                    width: 36.sp, height: 36.sp)
                .marginOnly(right: 36.sp)
          ])
              .marginOnly(top: 60.sp, bottom: 60.sp)
              .addGestureDetector(() => Get.back()),
          Container(
              margin: EdgeInsets.only(left: 32.sp, right: 32.sp),
              height: 2.sp,
              color: const Color(0xFFD8D8D8)),
          Image.asset('assets/images/home/scan/content_scuess.png',
                  width: 384.sp, height: 384.sp)
              .marginOnly(top: 84.sp),
          DefaultText('绑定成功！'.tr, 48.sp,
              textColor: Colors.white, fontWeight: FontWeight.w700),
          DefaultText(SR.backMain.replaceAll('xxxx', '${timerNum}S'), 48.sp,
              textColor: Colors.white, fontWeight: FontWeight.w700)
        ]));
  }
}

class CodeScanResult extends StatefulWidget {
  const CodeScanResult({super.key});

  @override
  State<CodeScanResult> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<CodeScanResult> {
  Timer? timer;
  int timerNum = 3;
  @override
  void initState() {
    super.initState();
    startTimer();
  }

  ///开始计时
  void startTimer() {
    timer?.cancel();
    // 每隔一秒更新倒计时数字
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (timerNum > 0) {
        setState(() {
          timerNum--;
        });
      } else {
        // 倒计时结束，取消定时器
        timer.cancel();
        timerNum = 3;
        Get.back();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return ScanResulOthertWidget.contentSuccessChild(timerNum);
  }
}
